var ip =  "http://localhost:8066/";

var API_SERVER_URL = ip;


var SERVER_URL ="http://localhost:63342/prime/";

var ATTACHMENT_PATH=API_SERVER_URL+'ftp/uploadFiles/';
var token = JSON.parse(localStorage.getItem("token"));
var JwtAuthorizations = JSON.parse(localStorage.getItem("JwtAuthorization"));
var PRIVATE_HEADERS = {"JwtAuthorization":JwtAuthorizations,"Authorization":token};
var SHOW_LOGIN_TIP = false;
function getRequestHears(redirect){
	var headers = {};
	var token = localStorage.getItem("token");
	if(token){
		headers.Authorization = JSON.parse(token);
	}else{
		if(redirect==true && !SHOW_LOGIN_TIP){
			showLoginTip();
			return;
		}
	}

	var JwtAuthorization = localStorage.getItem("JwtAuthorization");
	if(JwtAuthorization){
		headers.JwtAuthorization = JSON.parse(JwtAuthorization);
	}else{
		if(redirect==true && !SHOW_LOGIN_TIP){
			showLoginTip();
			return;
		}
	}

	return headers;
}

function showLoginTip(){
	SHOW_LOGIN_TIP = true;
	if(window.top){
		window.top.layer.alert('请重新登录', {
		  closeBtn: 0
		}, function(){
			SHOW_LOGIN_TIP = false;
			window.location.href = SERVER_URL;
		});
	}else{
		layer.alert('请重新登录', {
		  closeBtn: 0
		}, function(){
			SHOW_LOGIN_TIP = false;
			window.location.href = SERVER_URL;
		});
	}
}

function clearToken(){
	localStorage.removeItem("token");
	localStorage.removeItem("JwtAuthorization");
}

function loadDict(){
	loadAllDict(false);
	loadAllDictType(false);
}

function loadAllDict(asyncType){
	var url = window.API_SERVER_URL + 'common/dict/getAllDict';
	$.ajax({
		cache : true,
		type : "GET",
		headers:window.PRIVATE_HEADERS,
		url : url,
		data : {},
		async : asyncType,
		success : function(data) {
			localStorage.setItem("dictMap", JSON.stringify(data));
		}
	});
}

function loadAllDictType(asyncType){
	url = window.API_SERVER_URL + 'common/dict/getAllDictTypeAsKey';
	$.ajax({
		cache : true,
		type : "GET",
		headers:window.PRIVATE_HEADERS,
		url : url,
		data : {},
		async : false,
		success : function(data) {
			localStorage.setItem("dictTypeMap", JSON.stringify(data));
		}
	});
}
/**
 * 可以根据字典类型查询本地缓存的字典，返回其类型的字典列表
 * @param dictType
 * @returns
 */
function getDictTypeFromLocalStorage(dictType){
	var json = localStorage.getItem("dictTypeMap");
	var map = JSON.parse(json);
	var result = map[dictType];
	if(!result){
		loadAllDictType(true);
	}
	json = localStorage.getItem("dictTypeMap");
	map = JSON.parse(json);
	result = map[dictType];
	return result;
}

/**
 * 可以根据字典类型和值查询本地缓存的字典,返回相应的字典
 * @param dictId
 * @returns
 */
function getDictFromLocalStorage(dictType,value){
	var json = localStorage.getItem("dictMap");
	var map = JSON.parse(json);
	var key = dictType+"-"+value;
	var result = map[key];
	if(!result){
		loadAllDict(true);
	}
	json = localStorage.getItem("dictMap");
	map = JSON.parse(json);
	result = map[key];
	return result;
}

/**
 * 可以根据字典类型和值查询本地缓存的字典,返回相应的字典
 * @param dictId
 * @returns
 */
function getDictNameFromLocalStorage(dictType,value,defaultValue){
	var result = getDictFromLocalStorage(dictType,value);
	if(!result){
		return defaultValue;
	}
	return result.name;
} 

/**
 * 
 * @param selectId select控件的ID
 * @param dictType 字典类型
 * @param value 需要选中的值
 * @returns
 */
function selectAddOption(selectId,dictType,value){
	var list = getDictTypeFromLocalStorage(dictType);
	if(list){
		for (var i = 0; i < list.length; i++) {
			if(list[i].value == value){
				$("#"+selectId).append("<option value='"+list[i].value+"' selected='selected'>"+list[i].name+"</option>");
			}else{
				$("#"+selectId).append("<option value='"+list[i].value+"'>"+list[i].name+"</option>");
			}
		}
	}
}

function serializeMap(id){
	var obj = $('#'+id).serializeArray();
	var object = new Object();
	for(var i=0;i<obj.length;i++){
		object[obj[i].name] = obj[i].value; 
	}
	return object;
}

var vm;
//通过获取用户权限判断是否显示按钮的方法
function showButton(ele){
	//从本地获取用户权限,并将其转化为数组形式
	var permissionsArr = JSON.parse(localStorage.getItem("permissions"));
	//实例化vue对象
	vm = new Vue({
		//指定vue作用区域,注意:主标签不能是body标签
		el: ele,
		//将获取到的权限数组赋值给permissions字段(此字段可以在html中直接使用)
		data: {permissions: permissionsArr},
		methods:{
			isShowFun: function (permissionsId){
				return this.$data.permissions.indexOf(permissionsId) != -1 ? true : false;
			}
		}
	});
}

/**
 * 验证区域内元素权限，如果有权限则展示，没权限则删除元素节点
 * @param contentId
 */
function validateDomsPermission(contentId) {
    var permissionsArr = JSON.parse(localStorage.getItem("permissions"));
    var doms = $(contentId).find('[permission]');
    $.each(doms,function (index,dom) {
    	var permissionsId = $(dom).attr('permission');
		var permitted = permissionsArr.indexOf(permissionsId) != -1 ? true : false;
		if(permitted==true){
			$(dom).show();
		}else{
            $(dom).remove();
		}
    });

}


function isEmpty(value) {
    return ((value === undefined || value === null || value === "" || value === "undefined") ? true : false);
}
var options= {
    	tableID: undefined,
        url: undefined,
        method: undefined,
        columns: undefined,
        queryParams: undefined,
        contentType: undefined
}
function initOption(option) {
    options.tableID = option.tableID;
    options.url = ip+option.url;
    options.method = isEmpty(option.method) == true ? "post" : "get";
    options.queryParams = option.queryParams;
    options.columns = option.columns;
    if (isEmpty(option.contentType)) {
        this.options.contentType = "application/json; charset=utf-8";
    } else {
        if (option.contentType == "json") {
            this.options.contentType = "application/json; charset=utf-8";
        }
        if (option.contentType == "text") {
            this.options.contentType = "application/x-www-form-urlencoded";
        }
    }
}
function loadTable(option) {
    this.initOption(option);
    console.log(options);
    alert(JSON.stringify(options.columns));
    $('#' + options.tableID).bootstrapTable({
        url: options.url,         //请求后台的URL（*）
        method: options.method,                      //请求方式（*）
        data: "rows",
        dataType: "json",
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        queryParamsType: "",
        ajaxOptions: {
            headers: getRequestHears()
        },
        contentType: options.contentType,
        queryParams: initRequestParam, //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 2,
        pageList: [20],
        strictSearch: true,
        showColumns: true,                  //是否显示所有的列
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        columns: options.columns,
        onLoadSuccess: function (data) { //加载成功时执行
           alert("加载数据成功");
        },
        onLoadError: function (data) { //加载失败时执行
            alert("加载数据失败", {time: 1500, icon: 2});
        }

    });
}

 function initRequestParam(params) {
    if (options.contentType == "application/json; charset=utf-8") {
        return getParamsJson(options.queryParams, params);
    }
    return getParams(options.queryParams, params);
}


function getParamsJson(elemetnIds, page) {
    var params = new Map();
    if (!isEmpty(elemetnIds) && elemetnIds.length > 0) {
        for (var i = 0; i < elemetnIds.length; i++) {
            if (this.checkEmlementValue(elemetnIds[i])) {
                params.put(elemetnIds[i], $("#" + elemetnIds[i]).val())
            }
        }
    }
    if (page) {
        params.put("pageNum", page.pageNumber);
        params.put("pageSize", page.pageSize);
    }
    return this.parseMapToJson(params);
}
function checkEmlementValue(elementId) {
    var value = $.trim($("#" + elementId).val());
    if (value) {
        return true;
    }
    return false;
}
function parseMapToJson(map) {
    var str = "{";
    var elements = map.elements;
    for (var i = 0; i < elements.length; i++) {
        if (i == elements.length - 1) {
            str += '"' + elements[i].key + '":"' + elements[i].value + '"';
        } else {
            str += '"' + elements[i].key + '":"' + elements[i].value + '",';
        }
    }
    str += "}";
    return str;
}